package com.jack.vipmis.vip.card.service;

import org.apache.commons.lang3.StringUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.stereotype.Service;

import com.jack.vipmis.common.entity.search.SearchOperator;
import com.jack.vipmis.common.entity.search.Searchable;
import com.jack.vipmis.common.service.BaseService;
import com.jack.vipmis.vip.card.entity.Discount;
import com.jack.vipmis.vip.card.repository.DiscountRepository;

/**
 * 
 * @author JackLiang
 * @date 2014-6-16
 * @version 1.0
 */
@Service
public class DiscountService extends BaseService<Discount, Long> {

	private DiscountRepository getDiscountRepository() {
		return (DiscountRepository) baseRepository;
	}

	public Discount findByDisTitle(String disTitle) {
		return getDiscountRepository().findByDisTitle(disTitle);
	}

	/**
	 * 分页查询
	 * 
	 * @param page
	 * @param pageSize
	 * @param sortType
	 * @return
	 */
	public Page<Discount> getDiscount(int page, int pageSize, int type, Long bsId, String x, String y,//
			String con, String text) {

		Searchable search = Searchable.newSearchable();
		//
		if (StringUtils.isNotBlank(con) && con.equals("1")) {
			// x
			search.addSearchFilter("bsdistanceX", SearchOperator.gte,
					Double.parseDouble(StringUtils.isNotBlank(x) ? x : "0") - 0.01);

			search.addSearchFilter("bsdistanceX", SearchOperator.lte,
					Double.parseDouble(StringUtils.isNotBlank(x) ? x : "0") + 0.01);
			// y
			search.addSearchFilter("bsdistanceY", SearchOperator.gte,
					Double.parseDouble(StringUtils.isNotBlank(y) ? y : "0") - 0.01);

			search.addSearchFilter("bsdistanceY", SearchOperator.lte,
					Double.parseDouble(StringUtils.isNotBlank(y) ? y : "0") + 0.01);
		}
		// 根据下载次数
		if (StringUtils.isNotBlank(con) && con.equals("2")) {
			search.addSort(Direction.DESC, "disDownLoadCount");
		}
		// 根据创建时间
		if (StringUtils.isNotBlank(con) && con.equals("3")) {
			search.addSort(Direction.DESC, "createTime");
		}
		// 根据文字内容进行模糊查询
		if (StringUtils.isNotBlank(con) && con.equals("4")) {
			search.addSearchFilter("disTitle", SearchOperator.like, text);
		}
		search.addSearchFilter("disType", SearchOperator.eq, type);
		if (bsId != 0L) {
			search.addSearchFilter("business.id", SearchOperator.eq, bsId);
		}
		search.setPage((page - 1), pageSize);
		return getDiscountRepository().findAll(search);
	}
}
